const baseIP = '172.25.144.1'
const baseURL = `http://${baseIP}:8080`

// 请求封装
const request = async (options) => {
    try {
        const { url, method = 'GET', data, header = {} } = options
        const defaultHeader = {
            'Content-Type': 'application/json'
        }

        console.log('Request URL:', `${baseURL}${url}`)
        console.log('Request Data:', data)

        const res = await uni.request({
            url: `${baseURL}${url}`,
            method,
            data,
            header: { ...defaultHeader, ...header }
        })

        console.log('Response:', res)

        // 判断请求是否成功
        if (res.statusCode >= 200 && res.statusCode < 300) {
            // 判断业务状态码
            if (res.data.code === 200 || res.data.code === '200') {
                return res.data
            } else {
                throw new Error(res.data.msg || '请求失败')
            }
        } else {
            throw new Error(`${res.statusCode}: ${res.data.msg || '网络请求失败'}`)
        }
    } catch (error) {
        console.error('请求失败:', error)
        // 统一错误提示
        uni.showToast({
            title: error.message || '请求失败',
            icon: 'none'
        })
        throw error
    }
}

// 封装 GET 请求
const get = (url, params = {}) => {
    // 将参数转换为查询字符串
    const queryString = Object.keys(params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&')

    const fullUrl = queryString ? `${url}?${queryString}` : url
    return request({ url: fullUrl, method: 'GET' })
}

// 封装 POST 请求
const post = (url, data) => {
    return request({ url, method: 'POST', data })
}

// 封装 PUT 请求
const put = (url, data) => {
    return request({ url, method: 'PUT', data })
}

// 封装 DELETE 请求
const del = (url, params = {}) => {
    const queryString = Object.keys(params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&')

    const fullUrl = queryString ? `${url}?${queryString}` : url
    return request({ url: fullUrl, method: 'DELETE' })
}

// 文件上传封装
const upload = async (url, filePath, formData = {}) => {
    try {
        const res = await uni.uploadFile({
            url: `${baseURL}${url}`,
            filePath,
            name: 'file',
            formData,
            header: {
                'content-type': 'multipart/form-data'
            }
        })

        const result = JSON.parse(res.data)
        if (result.code === 200 || result.code === '200') {
            return result
        } else {
            throw new Error(result.msg || '上传失败')
        }
    } catch (error) {
        console.error('上传失败:', error)
        uni.showToast({
            title: error.message || '上传失败',
            icon: 'none'
        })
        throw error
    }
}

export default {
    get,
    post,
    put,
    delete: del,
    upload,
    baseURL
}
